package com.mofang.powerdekorhelper.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;

import com.mofang.powerdekorhelper.R;
import com.mofang.powerdekorhelper.activity.login.LoginActivity;
import com.mofang.powerdekorhelper.base.BaseActivity;
import com.mofang.powerdekorhelper.service.DialogService;
import com.mofang.powerdekorhelper.utils.ConnectionUtils;
import com.mofang.powerdekorhelper.utils.DialogUtils;
import com.mofang.powerdekorhelper.utils.SharePerforenceUtils;
import com.mofang.powerdekorhelper.utils.UrlTools;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 开屏页
 */

public class SplashActivity extends BaseActivity {

    @BindView(R.id.start_app_pbar)
    ProgressBar mProgressBar;

    String launchIntent;
    String articleId;

    @Override
    public void initView() {
        inflateLayout(R.layout.activity_splash_layout);
    }

    @Override
    public void initData() {

        launchIntent = getIntent().getStringExtra("LaunchIntent");

        articleId = getIntent().getStringExtra("ArticleId");

        mProgressBar.setVisibility(View.VISIBLE);

        handler.sendEmptyMessageDelayed(1, 1500);

        Intent intent = new Intent(this, DialogService.class);
        this.startService(intent);
    }

    @OnClick(R.id.start_app_root)
    void onclick(View view) {

        boolean isLogin = SharePerforenceUtils.getInstance(this).getLogin();
        if (isLogin) {
            toActivity(SplashActivity.this, MainActivity.class);
        } else {
            toActivity(SplashActivity.this, LoginActivity.class);
        }

        mProgressBar.setVisibility(View.GONE);
        finish();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            boolean isLogin = SharePerforenceUtils.getInstance(SplashActivity.this).getLogin();
            if (isLogin) {
                Integer userId = SharePerforenceUtils.getInstance(SplashActivity.this).getUserID();
                if (userId != -1) {
                    DialogUtils dialogUtils = DialogUtils.getInstance();
                    if (!dialogUtils.ispDialogShow()) {
                        ConnectionUtils connectionUtils = ConnectionUtils.getInstance();
                        connectionUtils.init(SplashActivity.this, UrlTools.WSUrl + userId);
                        connectionUtils.connect();
                    }
                }
                startActivity(new Intent(SplashActivity.this, MainActivity.class)
                        .putExtra("LaunchIntent", launchIntent)
                        .putExtra("ArticleId", articleId));

            } else {
                toActivity(SplashActivity.this, LoginActivity.class);
            }

            mProgressBar.setVisibility(View.GONE);

            finish();
        }
    };
}
